<script setup>
import * as echarts from 'echarts'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { Refresh } from '@element-plus/icons-vue'
import Robot from '@/assets/svg/robot-white.svg'
import Battery from '@/assets/svg/电池.svg'
import {
  chargeRobot,
  createRobot,
  getRobotBatteryThresholdCount,
  getRobotCount,
  getRobotsPage,
  getRobotStatusDistribution,
  getRobotDetail, // 假设新增的API获取机器人详情
  getRobotAlertId,
  getRobotBatteryDistribution
} from '@/api/robot'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useRobotStore } from '@/stores/modules/robot'

const localIcons = { Robot, Battery }
const getIcon = (iconName) => {
  if (localIcons[iconName]) return localIcons[iconName]
  return ElementPlusIconsVue[iconName]
}

// 状态数据
const statistics = ref([
  {
    title: '待机机器人',
    value: 25,
    icon: 'Robot',
    trend: 'up',
    percentage: 10,
    bgColor: '#4834d4'
  },
  {
    title: '任务中机器人',
    value: 12,
    icon: 'SetUp',
    trend: 'down',
    percentage: 5,
    bgColor: '#20bf6b'
  },
  {
    title: '低电量告警',
    value: 3,
    icon: 'Warning',
    trend: 'up',
    percentage: 20,
    bgColor: '#eb3b5a'
  },
  {
    title: '异常状态机器人',
    value: 2,
    icon: 'Close',
    trend: 'down',
    percentage: 15,
    bgColor: '#fa8231'
  }
])

const robotList = ref()
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const pieChartRef = ref(null)
const statusDistribution = ref([])

// 抽屉相关
const drawerVisible = ref(false)
const currentRobot = ref(null)

const queryRobotStatusDistribution = async () => {
  const { data } = await getRobotStatusDistribution()
  statusDistribution.value = data
  initPieChart()
}

const barChartRef = ref(null) // 新增：电量分布图
// 新增：电量分布静态数据
const batteryDistribution = ref({
  ranges: ['0-20%', '20-40%', '40-60%', '60-80%', '80-100%'],
  counts: [3, 5, 8, 6, 4] // 静态数据：假设25个机器人分布
})

const handleResize = () => {
  if (pieChartRef.value) {
    const pieChart = echarts.getInstanceByDom(pieChartRef.value)
    if (pieChart) pieChart.resize()
  }
  if (barChartRef.value) {
    // 新增：调整电量分布图大小
    const barChart = echarts.getInstanceByDom(barChartRef.value)
    if (barChart) barChart.resize()
  }
}

// 新增：初始化电量分布柱状图
const initBarChart = () => {
  if (!barChartRef.value) return
  const existingChart = echarts.getInstanceByDom(barChartRef.value)
  if (existingChart) existingChart.dispose()

  const barChart = echarts.init(barChartRef.value)
  const option = {
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    xAxis: {
      type: 'category',
      data: batteryDistribution.value.ranges,
      axisLabel: { color: '#1f2a44' }
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#1f2a44' }
    },
    series: [
      {
        name: '机器人数量',
        type: 'bar',
        barWidth: '60%',
        data: batteryDistribution.value.counts.map((count, index) => ({
          value: count,
          itemStyle: {
            color: {
              '0-20%': '#eb3b5a',
              '20-40%': '#fa8231',
              '40-60%': '#f7b731',
              '60-80%': '#20bf6b',
              '80-100%': '#4834d4'
            }[batteryDistribution.value.ranges[index]]
          }
        })),
        itemStyle: { borderRadius: [4, 4, 0, 0] }
      }
    ]
  }
  barChart.setOption(option)
}

const queryRobotStat = async () => {
  const res1 = await getRobotBatteryThresholdCount(30)
  statistics.value[2].value = res1.data
  const res2 = await getRobotCount('IDLE')
  statistics.value[0].value = res2.data
  const res3 = await getRobotCount('WORKING')
  statistics.value[1].value = res3.data
  const res4 = await getRobotCount('OFFLINE')
  statistics.value[3].value = res4.data
}

const queryBatteryDistribution = async () => {
  const { data } = await getRobotBatteryDistribution()
  batteryDistribution.value = data
  initBarChart()
}

onMounted(() => {
  queryRobots()
  queryRobotStatusDistribution()
  queryRobotStat()
  queryBatteryDistribution()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (pieChartRef.value) {
    const pieChart = echarts.getInstanceByDom(pieChartRef.value)
    if (pieChart) pieChart.dispose()
  }
  if (barChartRef.value) {
    // 新增：销毁电量分布图
    const barChart = echarts.getInstanceByDom(barChartRef.value)
    if (barChart) barChart.dispose()
  }
})

const initPieChart = () => {
  if (!pieChartRef.value) return
  const existingChart = echarts.getInstanceByDom(pieChartRef.value)
  if (existingChart) existingChart.dispose()

  const pieChart = echarts.init(pieChartRef.value)
  const option = {
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', right: 10, top: 'center' },
    series: [
      {
        name: '机器人状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        label: { show: false, position: 'center' },
        emphasis: { label: { show: true, fontSize: 16, fontWeight: 'bold' } },
        labelLine: { show: false },
        data: statusDistribution.value.map((item) => ({
          value: item.count,
          name: item.status,
          itemStyle: {
            color:
              {
                待机: '#4834d4',
                执行任务: '#20bf6b',
                充电: '#0fb9b1',
                离线: '#95a5a6'
              }[item.status] || '#95a5a6'
          }
        }))
      }
    ]
  }
  pieChart.setOption(option)
}

const getStatusType = (status) =>
  ({
    待机: 'success',
    执行任务: 'primary',
    充电中: 'warning',
    离线: 'info'
  })[status] || 'info'

const getBatteryStatus = (battery) => {
  if (battery <= 20) return 'exception'
  if (battery <= 50) return 'warning'
  return 'success'
}

const getAlertTypeTag = (type) =>
  ({
    化工火灾: 'danger',
    森林火灾: 'warning',
    建筑火灾: 'info',
    车辆火灾: 'success'
  })[type] || ''

const getAlertStatusTag = (priority) =>
  ({
    待处理: 'danger',
    处理中: 'warning',
    已处理: 'info'
  })[priority] || ''

const viewDetail = async (robot) => {
  try {
    const { data } = await getRobotDetail(robot.id) //
    // 假设这是获取机器人详情的API
    console.log(data)
    currentRobot.value = data
    drawerVisible.value = true
  } catch (error) {
    ElMessage.error('获取机器人详情失败')
  }
}

const chargeRobotByRobot = async (robot) => {
  if (robot.batteryLevel < 80) {
    await chargeRobot(robot.id, 100)
    ElMessage.success('机器人已启动充电')
    queryRobots()
    queryRobotStatusDistribution()
    queryRobotStat()
    queryBatteryDistribution()
  } else {
    ElMessage.warning('机器人电量健康，无需充电')
  }
}

const videoOnline = async (robot) => {
  if (robot.status != '执行任务') {
    ElMessage.warning('无法开启视频监控')
    return
  }
  const robotStore = useRobotStore()
  robotStore.setRobotInfo(robot)
  const res = await getRobotAlertId(robot.id)
  robotStore.setAlertId(res.data)
  console.log(robotStore.robotInfo)
  router.push('/robot/video')
}

const queryRobots = async () => {
  const { data } = await getRobotsPage(currentPage.value, pageSize.value)
  total.value = data.total
  robotList.value = data.list
}

// 添加机器人相关逻辑
const dialogVisible = ref(false)
const newRobot = ref({ name: '', location: '仓库A区' })
const locationOptions = [
  '仓库A区',
  '仓库B区',
  '仓库C区',
  '仓库D区',
  '仓库E区',
  '仓库F区'
]

const addRobot = async () => {
  await createRobot({
    robotName: newRobot.value.name,
    location: newRobot.value.location
  })
  ElMessage.success('机器人添加成功')
  dialogVisible.value = false
  queryRobots()
  queryRobotStatusDistribution()
  queryRobotStat()
  queryBatteryDistribution()
}
</script>

<template>
  <div class="monitor-page">
    <!-- 顶部卡片 -->
    <section class="stat-cards">
      <div v-for="stat in statistics" :key="stat.title" class="stat-card">
        <div class="card-content">
          <div class="stat-icon" :style="{ backgroundColor: stat.bgColor }">
            <el-icon><component :is="getIcon(stat.icon)" /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-title">{{ stat.title }}</div>
          </div>
          <!-- <div
            class="stat-trend"
            :class="{ up: stat.trend === 'up', down: stat.trend === 'down' }"
          >
            <el-icon
              ><component
                :is="stat.trend === 'up' ? getIcon('Top') : getIcon('Bottom')"
            /></el-icon>
            {{ stat.percentage }}%
          </div> -->
        </div>
      </div>
    </section>

    <!-- 主要内容区 -->
    <section class="main-content">
      <!-- 新增：图表行 -->
      <div class="chart-row">
        <el-card class="status-card" shadow="none">
          <template #header>
            <div class="card-header"><span>机器人实时状态分布</span></div>
          </template>
          <div ref="pieChartRef" class="pie-chart"></div>
        </el-card>
        <el-card class="battery-card" shadow="none">
          <template #header>
            <div class="card-header"><span>机器人电量分布</span></div>
          </template>
          <div ref="barChartRef" class="bar-chart"></div>
        </el-card>
      </div>

      <el-card class="monitor-list" shadow="none">
        <template #header>
          <div class="card-header">
            <span>实时监控列表</span>
            <div class="header-actions">
              <el-button type="primary" @click="dialogVisible = true"
                >添加机器人</el-button
              >
              <el-button type="primary" :icon="Refresh" @click="queryRobots"
                >刷新</el-button
              >
            </div>
          </div>
        </template>
        <el-table
          :data="robotList"
          class="modern-table"
          stripe
          @row-click="viewDetail"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column prop="id" label="机器人ID" width="100" />
          <el-table-column prop="robotName" label="名称" min-width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" round>{{
                row.status
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="batteryLevel" label="电量" width="180">
            <template #default="{ row }">
              <el-progress
                :percentage="row.batteryLevel"
                :status="getBatteryStatus(row.batteryLevel)"
                :show-text="false"
              />
            </template>
          </el-table-column>
          <el-table-column prop="location" label="当前位置" width="150" />
          <el-table-column
            prop="lastActiveTime"
            label="最后活动时间"
            min-width="250"
          />
          <el-table-column label="操作" min-width="200" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click.stop="viewDetail(row)"
                >详情</el-button
              >
              <el-button link type="primary" @click.stop="videoOnline(row)"
                >实时画面</el-button
              >
              <el-button
                link
                type="primary"
                @click.stop="chargeRobotByRobot(row)"
                >充电</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next"
          class="pagination"
          @size-change="queryRobots"
          @current-change="queryRobots"
        />
      </el-card>
    </section>

    <!-- 添加机器人弹窗 -->
    <el-dialog title="添加机器人" v-model="dialogVisible" width="30%">
      <el-form :model="newRobot" label-width="100px">
        <el-form-item label="机器人名称">
          <el-input v-model="newRobot.name" placeholder="请输入机器人名称" />
        </el-form-item>
        <el-form-item label="位置">
          <el-select v-model="newRobot.location" placeholder="请选择位置">
            <el-option
              v-for="item in locationOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRobot">提交</el-button>
      </template>
    </el-dialog>

    <!-- 机器人详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      size="50%"
      :destroy-on-close="true"
      class="modern-drawer"
    >
      <template #header>
        <div class="drawer-header">
          <h4>机器人详情</h4>
          <el-tag :type="getStatusType(currentRobot?.status)" round>{{
            currentRobot?.status
          }}</el-tag>
        </div>
      </template>

      <div class="drawer-content" v-if="currentRobot">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border class="modern-descriptions">
          <el-descriptions-item label="机器人ID">{{
            currentRobot.id
          }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{
            currentRobot.robotName
          }}</el-descriptions-item>
          <el-descriptions-item label="当前位置">{{
            currentRobot.location
          }}</el-descriptions-item>
          <el-descriptions-item label="最后活动时间">{{
            currentRobot.lastActiveTime
          }}</el-descriptions-item>
          <el-descriptions-item label="电量">
            <el-progress
              :percentage="currentRobot.batteryLevel"
              :status="getBatteryStatus(currentRobot.batteryLevel)"
            />
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRobot.status)">{{
              currentRobot.status
            }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 任务历史 -->
        <div class="detail-section">
          <h5>任务历史</h5>
          <el-table
            :data="currentRobot.alert"
            class="modern-table"
            stripe
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
          >
            <el-table-column prop="alertNo" label="警情编号" min-width="250" />
            <el-table-column prop="alertType" label="警情类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getAlertTypeTag(row.alertType)" round>{{
                  row.alertType
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="location" label="地点" min-width="120" />
            <el-table-column prop="createdTime" label="报警时间" width="180" />
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="{ row }">
                <el-tag :type="getAlertStatusTag(row.status)" round>{{
                  row.status
                }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="drawer-footer">
          <el-button type="primary" @click="drawerVisible = false"
            >关闭</el-button
          >
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.monitor-page {
  padding: 2.4rem;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 顶部卡片 */
.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 2.4rem;
  margin-bottom: 2.4rem;

  .stat-card {
    background: #ffffff;
    border-radius: 1.2rem;
    padding: 2rem;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s;

    &:hover {
      transform: translateY(-4px);
    }

    .card-content {
      display: flex;
      align-items: center;
      gap: 1.6rem;

      .stat-icon {
        width: 4.8rem;
        height: 4.8rem;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 3rem;
        flex-shrink: 0;
      }

      .stat-info {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 1rem;

        .stat-value {
          font-size: 2.8rem;
          font-weight: 700;
          color: #1f2a44;
          line-height: 1;
        }
        .stat-title {
          font-size: 2rem;
          color: #86909c;
        }
      }
    }
  }
}

/* 主要内容区 */
.main-content {
  display: flex;
  flex-direction: column;
  gap: 2.4rem;

  /* 新增：图表行 */
  .chart-row {
    display: flex;
    gap: 2.4rem;
    width: 100%;

    .status-card {
      flex: 0 0 40%; /* 左边饼图占 40% */
      border-radius: 12px;
      background: #ffffff;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

      .pie-chart {
        height: 30rem;
        width: 100%;
      }
    }

    .battery-card {
      flex: 1;
      border-radius: 12px;
      background: #ffffff;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

      .bar-chart {
        height: 30rem;
        width: 100%;
      }
    }
  }

  .monitor-list {
    border-radius: 12px;
    background: #ffffff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    max-width: 100%;
    overflow-x: auto;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 2rem;
    font-weight: 600;
    color: #1f2a44;
    padding: 0 1rem;

    .header-actions {
      display: flex;
      gap: 1rem;
    }

    .el-button {
      background: linear-gradient(135deg, #4834d4 0%, #6b5fe8 100%);
      border: none;
      color: #fff;
      border-radius: 6px;
      padding: 8px 16px;
      font-size: 1.6rem;

      &:hover {
        opacity: 0.9;
      }
    }
  }

  .modern-table {
    border-radius: 8px;
    overflow: hidden;

    :deep(.el-table__cell) {
      .cell {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 1.6rem;
      }

      .el-button {
        font-size: 1.6rem;
      }
    }

    :deep(.el-table__header th) {
      background: #fafafa;
      color: #1f2a44;
      font-weight: 600;
    }

    :deep(.el-table__row:hover) {
      background: #f9fafc;
    }

    .el-tag {
      border-radius: 6px;
      font-weight: 500;
    }
  }

  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
    padding: 0 16px;

    :deep(.el-pager li.is-active) {
      background: #4834d4;
      color: #fff;
    }

    @media screen and (max-width: 768px) {
      flex-direction: column;
      align-items: flex-end;
      gap: 8px;
    }
  }
}

/* 响应式设计 */
@media screen and (max-width: 1400px) {
  .monitor-page {
    .stat-cards {
      grid-template-columns: repeat(2, 1fr);
    }
    .chart-row {
      flex-direction: column; /* 小屏幕时恢复垂直排列 */
    }
  }
}

@media screen and (max-width: 768px) {
  .monitor-page {
    .stat-cards {
      grid-template-columns: 1fr;
    }
  }
}

/* 抽屉样式 */
.modern-drawer {
  :deep(.el-drawer__header) {
    padding: 1.6rem 2.4rem;
    border-bottom: 1px solid #f0f2f5;
    margin-bottom: 0;
  }

  .drawer-header {
    display: flex;
    align-items: center;
    gap: 1.2rem;

    h4 {
      margin: 0;
      font-size: 2rem;
      font-weight: 600;
      color: #1f2a44;
    }

    .el-tag {
      font-weight: 500;
      font-size: 1.6rem;
    }
  }

  .drawer-content {
    padding: 1rem;
    :deep(.el-descriptions__cell),
    :deep(.el-table__cell) {
      font-size: 1.6rem;

      .el-tag {
        font-size: 1.6rem;
      }
    }

    .detail-section {
      margin-top: 24px;

      h5 {
        font-size: 1.8rem;
        font-weight: 600;
        color: #1f2a44;
        margin-bottom: 12px;
      }

      .modern-table {
        border-radius: 8px;
        overflow: hidden;

        :deep(.el-table__header th) {
          background: #fafafa;
          color: #1f2a44;
          font-weight: 600;
          font-size: 1.6rem;
        }

        :deep(.el-table__row:hover) {
          background: #f9fafc;
        }
      }
    }

    .modern-descriptions {
      border-radius: 8px;
      overflow: hidden;

      :deep(.el-descriptions__cell) {
        border-color: #f0f2f5;
        padding: 12px;
      }

      :deep(.el-descriptions__label) {
        background: #fafafa;
        color: #1f2a44;
        font-weight: 500;
        font-size: 1.6rem;
      }
    }
  }

  .drawer-footer {
    padding: 0 24px 24px;
    display: flex;
    justify-content: flex-end;

    .el-button {
      background: linear-gradient(135deg, #4834d4 0%, #6b5fe8 100%);
      border: none;
      border-radius: 8px;
      padding: 10px 20px;
      font-size: 1.6rem;

      &:hover {
        opacity: 0.9;
      }
    }
  }
}
</style>
